package com.example.online_exam_system.config;

import com.example.online_exam_system.entity.StuExam;
import com.example.online_exam_system.service.StuExamService;
import com.example.online_exam_system.service.TestQuestionsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author lianglong
 * @date 2022-03-20
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Slf4j
public class ExamCheckScheduleTask {
    @Autowired
    StuExamService stuExamService;

    @Autowired
    TestQuestionsService testQuestionsService;
    //3.添加定时任务
    @Scheduled(cron = "0 */5 * * * ?")
    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        log.debug("执行静态定时任务时间: " + LocalDateTime.now());
        List<StuExam> list = stuExamService.queryExamCheck();
        list.forEach(stuExam -> {
            int questionId = stuExam.getQuestionid();
            String reply = stuExam.getReply();
            Map<String, Object> questionsByQuestionId = testQuestionsService.getQuestionsByQuestionId(String.valueOf(questionId));
            String type = MapUtils.getString(questionsByQuestionId,"type");
            if(type.equals("单选题")){
                String right = MapUtils.getString(questionsByQuestionId,"right");
                if(reply.equals(right)){
                    String score =  MapUtils.getString(questionsByQuestionId,"score");
                    stuExam.setScore(score);
                }else{
                    String score = "0";
                    stuExam.setScore(score);
                }
            }
        });
        int num= stuExamService.updateExamCheck(list);
        log.debug("此次定时任务更新条数 " +num);
        log.debug("定时任务执行完毕时间: " + LocalDateTime.now());

    }
}
